package com.zzcoder.mall.security.component;

import com.zzcoder.mall.common.dto.ResponseResult;
import com.zzcoder.mall.common.exception.VerifyCodeException;
import com.zzcoder.mall.common.util.JsonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        if (e instanceof VerifyCodeException) {
            writer.println(JsonUtil.toJSON(ResponseResult.fail(HttpServletResponse.SC_UNAUTHORIZED, "验证码错误")));
        } else {
            writer.println(JsonUtil.toJSON(ResponseResult.fail(HttpServletResponse.SC_UNAUTHORIZED, "用户名或密码错误")));
        }
        writer.flush();
        writer.close();
    }
}
